import { applyMiddleware, createStore } from "redux";
import axios from "axios";
import thunk from "redux-thunk";
import logger from "redux-logger";

const initState = {
  car: [],
};

export const fetchCar = () => {
  return async (dispatch) => {
    axios.get("/api/car").then((resp) => {
      dispatch({ type: "setCar", payload: resp.data.data });
    });
  };
};

const reducer = (prevState = initState, action) => {
  switch (action.type) {
    case "setCar": {
      return {
        ...prevState,
        car: action.payload,
      };
    }
    case 'addItem': {
      const item = prevState.car.find(v => v.id === action.payload.id);
      if(item) {
        item.count++
      } else {
        prevState.car.push(action.payload)
      }
      return {
        ...prevState,
        car: [...prevState.car]
      }
    }
    case 'subItem': {
      const item = prevState.car.find(v => v.id === action.payload.id);
      if(item) {
        item.count--
      } else {
        prevState.car.push(action.payload)
      }
      return {
        ...prevState,
        car: [...prevState.car]
      }
    }
    case 'switchItem': {
      const item = prevState.car.find(v => v.id === action.payload.id);
      if(item) {
        item.check = !item.check
      } else {
        prevState.car.push(action.payload)
      }
      return {
        ...prevState,
        car: [...prevState.car]
      }
    }
    case 'removeItem': {
      return {
        ...prevState,
        car: prevState.car.filter(v => v.id !== action.payload.id)
      }
    }
  }
  return prevState;
};

export const store = createStore(reducer, applyMiddleware(thunk, logger));
